/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 *
 * $Id: Text_Dummy.cpp,v 1.5 2009-07-20 15:27:00 morsko Exp $
 *
 * \file
 * \brief Dummy implementation for Text Server interface.
 * \author Matthieu Myrsky <matthieu.myrsky@tkk.fi>
 *
 * This implementation can act as an example / codebase for any
 * Text server based module implementation. This code follows a
 * pseudogood coding style, and also provides a basic parameter
 * parser that can be directly used with slight modifications.
 * 
 */
#include <stdio.h>
#include <stdlib.h>
#include "owndebug.h"
#include "TextServer.hpp"
#include "binbag.h"


//*****************************************************************************
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************
static int verbose = 1;
//*****************************************************************************
using namespace MaCI::Text;
//*****************************************************************************
std::string intToString(int aInt)
{
 
  std::string s;
  std::stringstream out;
  out << aInt;
  return out.str();
}
//*****************************************************************************

void showUsage()
{
  fprintf(stderr,"\n");
  fprintf(stderr,"Usage:\tText_Dummy [OPTIONS]\n");
  fprintf(stderr,"  [-S]\t\t\t\tUse Dummy as a text sender\n");
  fprintf(stderr,"  [-u addr]\t\t\tUse 'addr' as GIMnet AccessPoints address\n");
  fprintf(stderr,"  [-p port]\t\t\tUse 'port' as GIMnet AccessPoints port\n");
  fprintf(stderr,"  [-n name]\t\t\tUse 'name' as this nodes GIMnet name\n");
  fprintf(stderr,"  [-G name]\t\t\tUse 'name' as MaCIGroup for this service\n");
  fprintf(stderr,"  [-I name]\t\t\tUse 'name' as Instancename for this service\n");

  fprintf(stderr,"  [-v]\t\t\t\tIncrease verbosity by 1\n");
  fprintf(stderr,"  [-q]\t\t\t\tQuiet mode\n");
  fprintf(stderr, "\n\n");
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

int main(int argc, char *argv[])
{
 // GIMnet parameters
  std::string gimnetAP = "asrobo.hut.fi";
  int gimnetAPPort = 50002;
  std::string gimnetName = "";
  std::string maciGroupName;
  std::string interfaceInstanceName = "Dummy";
  // Objects
  bool run = true;
  bool isSender = false;



  gimi::GIMI g;
  MaCI::MaCICtrl::CMaCICtrlServer msc(&g);
  MaCI::Text::CTextServer textS(&msc, 0); 

  // Init Debug lib
  debugInit();
  debugSetGlobalDebugLvl(4);
  debugSetLogFilename("Text_Dummy.log");

  // Greet
  fprintf(stderr,
	  "\nText_Dummy - MaCI Text Interface implementation for Dummy - v0.00001\n");

  // Parse parameters
  bool parse = true;
  while(parse) {
    int c;
    c = getopt(argc, argv, "I:G:n:u:p:hqvS");
    switch(c) {

      /////////////////////////////////
      ////// Application specific /////
      /////////////////////////////////

    case 'S':
      isSender = true;
      break;

      /////////////////////////////////
      ///// GIMnet parameters /////////
      /////////////////////////////////
    case 'n':
      gimnetName = optarg;
      dPrint(3,"Using GIMnet Name '%s'", optarg);
      break;

    case 'u':
      gimnetAP = optarg;
      dPrint(3,"Using GIMnetAP address '%s'", optarg);
      break;

    case 'p':
      gimnetAPPort = atoi(optarg);
      dPrint(3,"Using GIMnetAP port '%d'", gimnetAPPort);
      break;
    case 'G':
      maciGroupName = optarg;
      dPrint(3,"Using MaCIGroupName '%s'", optarg);
      break;

    case 'I':
      interfaceInstanceName = optarg;
      dPrint(3,"Using InterfaceInstance Name '%s'", optarg);
      break;

      //////////////////////////////////
      //// GENERIC:                 ////
      //////////////////////////////////
    case 'v':
      // Increase only if not previously set to 0 (by 'quiet')
      if (verbose > 0)
	debugSetGlobalDebugLvl(++verbose);
      break;
      
    case 'q':
      verbose = 0;
      debugSetGlobalDebugLvl(0);
      break;
      
    case 'h':
    case '?':
      showUsage();
      exit(1);
      break;
      
    case -1:
      parse = false;
      break;
    }
  }

  msc.SetGroupName(maciGroupName);
  textS.SetInterfaceInstanceName(interfaceInstanceName);
  int r;
  if ( (r = g.connectToHubEx(gimnetAP, gimnetAPPort, gimnetName) ) != GIMI_OK) {
    dPrint(1,"Failed to connect to GIMnet AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
  } else {
    dPrint(2,"Succesfully connected to GIMnet at AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
    MaCI::EMaCIError e;
    if ( (e = textS.Open()) != MaCI::KMaCIOK) {
      dPrint(1,"Failed to Open TextServer instance! (%s)",
	     GetErrorStr(e).c_str());
      
    } else {
      ////// Execute test section ///////

      // Run as long as 'run' is set.
      int loopIndex = 1;
      while (run) {
	using namespace MaCI::Text;

	// Construct Data element
	CTextData textData;
        TReplyInfo aInfo;
	gim::binbag::CBinBag bb;
	
	// Now, sit back and wait for command to arrive (for 1000ms)
        if(isSender){
          std::string messageToSend = "MEssage number " + intToString(loopIndex);
          textS.SendText(messageToSend);
          dPrint(1,"Sent text '%s' to clients",messageToSend.c_str());
          loopIndex++;
          ownSleep_ms(5000);

        }else{
          e = textS.WaitCommand(textData,aInfo,1000);

          // Got command? (No timeout or error)
          if (e == MaCI::KMaCIOK) {
            dPrint(1,"Got command");
            const TCommand *cmd = textData.GetCommand();
            
            //	  textData.Print(1);
            assert(cmd != NULL);
            // Switch based on command type
            switch(cmd->cmd) {
              
            case KCommandSendText:{
              const TTextHeader *header = textData.GetTextHeader();
              std::string wholeSentence = "";
              for(unsigned int i = 0; i < header->number; i++){
                wholeSentence += std::string(textData.GetText(i)->text);
              }
              dPrint(1,"Got Command Send Text : '%s'", wholeSentence.c_str());
              
            dPrint(1,"Sending reply");
            
            
            textS.SendTextAccomplishedMessage(wholeSentence,
                                              aInfo);
            
            
            break;
            }
              
            case KCommandClearText:{
              dPrint(1,"Got Command CLEAR TEXT");
              break;
            }
            default:{
              dPrint(1,"No implementation for command %d!", cmd->cmd);
              break;
            }
            }


          } else if (e == MaCI::KMaCITimeout) {
            // No, timeout waiting for command. Print and wait again.
            dPrint(8,"Timeout waiting for Command");
            
          } else {
            // Quck? Some error occured? Print it, sleep an extra second and try again.
            dPrint(1,"Failed to WaitCommand()! (%s)",
                   GetErrorStr(e).c_str());
            ownSleep_ms(1000);
          }
        }
      
    
      }
    }
  }

  return 0;
}

//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

